package com.my.study.dev;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Carlos
 * @version 1.0.0
 * @date 2023/4/22 9:39
 */
public class TestLWL {

    static class Node {
        int id;
        int parentId;
        String name;
        List<Node> children;

        Node(int id, int parentId, String name) {
            this.id = id;
            this.parentId = parentId;
            this.name = name;
        }

        List<Node> getChildren() {
            return children;
        }

        void setChildren(List<Node> children) {
            this.children = children;
        }
    }
    
    public static void main(String[] args) {
        List<Node> nodeList = new ArrayList<>();
        
        nodeList.add(new Node(1,0, "AA"));
        nodeList.add(new Node(2,1, "BB"));
        nodeList.add(new Node(3,1, "CC"));
        nodeList.add(new Node(4,2, "DD"));

        nodeList.add(new Node(5,0, "EE"));
        nodeList.add(new Node(6,5, "FF"));
        nodeList.add(new Node(7,2, "GG"));
        nodeList.add(new Node(8,3, "HH"));
        
        print(nodeList);
    }
    
    private static void print(List<Node> nodeList) {
        int blank = 0;
        List<Node> nodes = getChildren(0, nodeList);

        for (Node node : nodes) {
            printChildren(node, blank, node.getChildren());
        }
    }
    
    private static void printChildren(Node root, int blank, List<Node> children) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < blank; i++) {
            sb.append("  ");
        }
        System.out.println(sb.toString() + root.name);
        int tmp = blank;
        for (Node child : children) {
            printChildren(child, ++blank, child.getChildren());
            blank = tmp;
        }
    }
    
    
    private static List<Node> getChildren(int parent, List<Node> nodeList) {
        List<Node> children = new ArrayList<>();
        for (Node node : nodeList) {
            if (parent == node.parentId) {
                children.add(node);
                node.setChildren(getChildren(node.id, nodeList));
            }
        }
        return children;
    }
    
}
